package com.example.vp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.vp.domian.enetity.User;
import com.example.vp.exception.CustomException;
import com.example.vp.service.CaptchaService;
import com.example.vp.service.LoginService;
import com.example.vp.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    @Resource
    private UserService userService;
    private CaptchaService captchaService;
    @Override
    public User login(User user) {
        User user1 = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername,user.getUsername()));
        System.out.println(user1.getPassword());
        if(ObjectUtils.isEmpty(user1)){
            throw new CustomException("用户不存在");
        }
        if(!user1.getPassword().equals(user.getPassword())){
            throw  new CustomException("密码错误");
        }
        return user1;
    }

    @Override
    public void captcha(String uuId, HttpServletResponse response) throws IOException {
        if (ObjectUtils.isEmpty(uuId))
            throw new IllegalArgumentException("uuid不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        BufferedImage image = captchaService.getCaptcha(uuId);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }
}
